/* 主应用逻辑 */
class MainApp {
    constructor() {
        this.init();
    }

    init() {
        this.bindEvents();
        this.initializeSlider();
        this.loadInitialData();
    }

    bindEvents() {
        // 轮播图控制
        document.querySelectorAll('.dot').forEach(dot => {
            dot.addEventListener('click', (e) => {
                const slideIndex = parseInt(e.target.dataset.slide);
                this.goToSlide(slideIndex);
            });
        });

        // CTA按钮点击
        document.querySelectorAll('.cta-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                this.scrollToProducts();
            });
        });

        // 我的订单链接点击
        const ordersLink = document.getElementById('ordersLink');
        if (ordersLink) {
            ordersLink.addEventListener('click', (e) => {
                e.preventDefault();
                this.goToOrders();
            });
        }

        // 页面滚动事件
        window.addEventListener('scroll', this.handleScroll.bind(this));

        // 窗口大小改变事件
        window.addEventListener('resize', this.handleResize.bind(this));
    }

    initializeSlider() {
        this.currentSlide = 0;
        this.slides = document.querySelectorAll('.slide');
        this.dots = document.querySelectorAll('.dot');
        
        // 自动轮播
        this.sliderInterval = setInterval(() => {
            this.nextSlide();
        }, 5000);
    }

    goToSlide(index) {
        // 移除当前活动状态
        this.slides[this.currentSlide].classList.remove('active');
        this.dots[this.currentSlide].classList.remove('active');
        
        // 设置新的活动状态
        this.currentSlide = index;
        this.slides[this.currentSlide].classList.add('active');
        this.dots[this.currentSlide].classList.add('active');
    }

    nextSlide() {
        const nextIndex = (this.currentSlide + 1) % this.slides.length;
        this.goToSlide(nextIndex);
    }

    scrollToProducts() {
        const productsSection = document.querySelector('.recommended-section');
        if (productsSection) {
            productsSection.scrollIntoView({ 
                behavior: 'smooth',
                block: 'start'
            });
        }
    }

    goToOrders() {
        // 检查用户是否已登录
        if (!window.authManager || !window.authManager.isAuthenticated()) {
            if (window.authManager) {
                window.authManager.showLoginModal();
            } else {
                alert('请先登录');
            }
            return;
        }
        
        // 跳转到订单页面
        window.location.href = 'orders.html';
    }

    handleScroll() {
        // 添加滚动效果
        const scrolled = window.pageYOffset;
        const parallax = document.querySelector('.hero-section');
        
        if (parallax) {
            const speed = scrolled * 0.5;
            parallax.style.transform = `translateY(${speed}px)`;
        }

        // 显示/隐藏回到顶部按钮
        this.toggleBackToTop(scrolled);
    }

    handleResize() {
        // 响应式处理
        this.adjustLayout();
    }

    adjustLayout() {
        const width = window.innerWidth;
        
        // 移动端优化
        if (width < 768) {
            document.body.classList.add('mobile');
        } else {
            document.body.classList.remove('mobile');
        }
    }

    toggleBackToTop(scrolled) {
        let backToTopBtn = document.getElementById('backToTop');
        
        if (!backToTopBtn) {
            backToTopBtn = document.createElement('button');
            backToTopBtn.id = 'backToTop';
            backToTopBtn.innerHTML = '<i class="fas fa-arrow-up"></i>';
            backToTopBtn.className = 'back-to-top';
            backToTopBtn.style.cssText = `
                position: fixed;
                bottom: 20px;
                right: 20px;
                width: 50px;
                height: 50px;
                border-radius: 50%;
                background: #ff6b35;
                color: white;
                border: none;
                cursor: pointer;
                display: none;
                z-index: 1000;
                transition: all 0.3s ease;
                box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
            `;
            
            backToTopBtn.addEventListener('click', () => {
                window.scrollTo({ top: 0, behavior: 'smooth' });
            });
            
            document.body.appendChild(backToTopBtn);
        }
        
        if (scrolled > 300) {
            backToTopBtn.style.display = 'block';
        } else {
            backToTopBtn.style.display = 'none';
        }
    }

    async loadInitialData() {
        try {
            // 加载推荐商品
            await this.loadRecommendedProducts();
            
            // 加载热门商品
            await this.loadTrendingProducts();
            
            // 同步购物车
            if (window.cartManager) {
                await window.cartManager.syncToBackend();
            }
            
        } catch (error) {
            console.error('加载初始数据失败:', error);
        }
    }

    async loadRecommendedProducts() {
        try {
            const result = await window.productManager.getRecommendedProducts();
            if (result.success) {
                const container = document.getElementById('recommendedProducts');
                if (container) {
                    window.productManager.renderProductGrid(container, result.data);
                }
            }
        } catch (error) {
            console.error('加载推荐商品失败:', error);
        }
    }

    async loadTrendingProducts() {
        try {
            const result = await window.productManager.getTrendingProducts();
            if (result.success) {
                const container = document.getElementById('trendingProducts');
                if (container) {
                    window.productManager.renderProductGrid(container, result.data);
                }
            }
        } catch (error) {
            console.error('加载热门商品失败:', error);
        }
    }

    // 显示折扣游戏
    showDiscountGame() {
        if (window.discountGame) {
            window.discountGame.showGameModal();
        }
    }

    // 工具方法
    formatPrice(price) {
        return `¥${price.toFixed(2)}`;
    }

    formatDate(date) {
        return new Date(date).toLocaleDateString('zh-CN');
    }

    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    throttle(func, limit) {
        let inThrottle;
        return function() {
            const args = arguments;
            const context = this;
            if (!inThrottle) {
                func.apply(context, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    }
}

// 订单管理
class OrderManager {
    constructor() {
        this.currentOrder = null;
        this.discount = 0;
        this.init();
    }

    init() {
        this.bindEvents();
    }

    bindEvents() {
        // 绑定结算相关事件
        document.addEventListener('click', (e) => {
            if (e.target.classList.contains('checkout-btn')) {
                this.startCheckout();
            }
        });
    }

    async startCheckout() {
        if (!window.authManager.isAuthenticated()) {
            window.authManager.showLoginModal();
            return;
        }

        const cartData = window.cartManager.getCartData();
        if (cartData.selectedItems.length === 0) {
            window.authManager.showNotification('请先选择要购买的商品', 'error');
            return;
        }

        // 显示折扣游戏选项
        this.showDiscountOption();
    }

    showDiscountOption() {
        const confirmed = confirm('是否要玩折扣游戏来获得优惠？');
        if (confirmed) {
            window.discountGame.showGameModal();
        } else {
            this.proceedToCheckout();
        }
    }

    applyDiscount(discountPercent) {
        this.discount = discountPercent;
        this.proceedToCheckout();
    }

    async proceedToCheckout() {
        try {
            const cartData = window.cartManager.getCartData();
            const selectedItems = cartData.selectedItems;
            
            if (selectedItems.length === 0) {
                window.authManager.showNotification('购物车为空', 'error');
                return;
            }

            // 跳转到结算页面
            window.location.href = `checkout.html?discount=${this.discount}`;
            
        } catch (error) {
            console.error('结算失败:', error);
            window.authManager.showNotification('结算失败，请稍后重试', 'error');
        }
    }

    async createOrder(orderData) {
        try {
            const result = await api.createOrder(orderData);
            if (result.success) {
                // 清空购物车中的已下单商品
                const selectedItems = window.cartManager.getSelectedItems();
                selectedItems.forEach(item => {
                    window.cartManager.removeFromCart(item.product_id);
                });
                
                return { success: true, data: result.data };
            } else {
                return { success: false, error: result.error };
            }
        } catch (error) {
            return { success: false, error: error.message };
        }
    }
}

// 创建全局实例
window.orderManager = new OrderManager();

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    // 创建主应用实例
    window.mainApp = new MainApp();
    
    // 初始化其他组件
    if (window.authManager) {
        window.authManager.updateUI();
    }
    
    if (window.cartManager) {
        window.cartManager.updateCartCount();
    }
    
    // 添加页面加载动画
    document.body.classList.add('loaded');
    
    // 预加载关键资源
    this.preloadResources();
});

// 预加载资源
function preloadResources() {
    const images = [
        'https://via.placeholder.com/300x200?text=商品图片1',
        'https://via.placeholder.com/300x200?text=商品图片2',
        'https://via.placeholder.com/300x200?text=商品图片3'
    ];
    
    images.forEach(src => {
        const img = new Image();
        img.src = src;
    });
}

// 错误处理
window.addEventListener('error', (e) => {
    console.error('页面错误:', e.error);
});

window.addEventListener('unhandledrejection', (e) => {
    console.error('未处理的Promise拒绝:', e.reason);
});

// 性能监控
if ('performance' in window) {
    window.addEventListener('load', () => {
        setTimeout(() => {
            const perfData = performance.getEntriesByType('navigation')[0];
            console.log('页面加载时间:', perfData.loadEventEnd - perfData.loadEventStart, 'ms');
        }, 0);
    });
}
